/******************************************************************
 * Created by: DO HOANG HAI                                       
 * Date of Creation: 18/Aug/2007                                    
 * Date of last modification: 22/Feb/2008
 *                                                                
 * Description: Main form of the program
 ******************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using Pbdms.Common;
using Pbdms.Common.DataObject;
using System.Collections;
using System.Threading;
using System.Data;
using Pbdms.BusinessLogic.PeerMS;
using Pbdms.Common.CryptoUtils;
using Pbdms.Common.SharedVariables;
using System.IO;
using System.Net.Sockets;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Bcpg;
using System.Runtime.InteropServices;
using Pbdms.NetworkDealer;
namespace Pbdms.Forms

{
    public partial class FrmMain : Form
    {
        public ArrayList arlOfMissingFiles = new ArrayList();
        private bool isMinimized = false;
        // added by chee hong
        public static PeerTracker PrTracker;
        public Thread PeerTrackerThread;
 
        public Pbdms.Forms.Views.FrmBuddyStatus frmBuddiesStatus;

        public Pbdms.Forms.Tools.FrmKeyManager frmKeyManager=null;
        public delegate void  DelegateWorker(object sender, string args);
        public delegate void NetworkMessageHandler(object source, NetworkMessage message);
        public delegate void BrowseWorker(object sender, ResultItem Result);
        public Pbdms.Forms.Views.FrmViewFeeds frmfeeds = null;
        public Pbdms.Forms.Views.FrmViewAnItem frmViewAnItem =null;
        public Pbdms.Forms.Views.FrmInbox frmInbox = null;
        public Pbdms.Forms.Tools.FrmFileTransfers frmFileTransfer = null;
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
        [StructLayout(LayoutKind.Sequential)]
        public struct FLASHWINFO
        {
            public UInt32 cbSize;
            public IntPtr hwnd;
            public UInt32 dwFlags;
            public UInt32 uCount;
            public UInt32 dwTimeout;
        }
        //Stop flashing. The system restores the window to its original state.
        public const UInt32 FLASHW_STOP = 0;
        //Flash the window caption.
        public const UInt32 FLASHW_CAPTION = 1;
        //Flash the taskbar button.
        public const UInt32 FLASHW_TRAY = 2;
        //Flash both the window caption and taskbar button.
        //This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
        public const UInt32 FLASHW_ALL = 3;
        //Flash continuously, until the FLASHW_STOP flag is set.
        public const UInt32 FLASHW_TIMER = 4;
        //Flash continuously until the window comes to the foreground.
        public const UInt32 FLASHW_TIMERNOFG = 12; 
        public static bool FlashWindowEx(Form frm)
        {
            IntPtr hWnd = frm.Handle;
            FLASHWINFO fInfo = new FLASHWINFO();

            fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
            fInfo.hwnd = hWnd;
            fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMER;
            fInfo.uCount = UInt32.MaxValue;
            fInfo.dwTimeout = 0;

            return FlashWindowEx(ref fInfo);
        }

        public bool DunFlashWindowEx(Form frm)
        {
            IntPtr hWnd = frm.Handle;
            FLASHWINFO fInfo = new FLASHWINFO();

            fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
            fInfo.hwnd = hWnd;
            fInfo.dwFlags = FLASHW_STOP;
            fInfo.uCount = UInt32.MaxValue;
            fInfo.dwTimeout = 0;

            return FlashWindowEx(ref fInfo);
        }

        public FrmMain()
        {

            InitializeComponent();
          
            Pbdms.Common.Global.paintBackGround(this);
          
            frmKeyManager= new Pbdms.Forms.Tools.FrmKeyManager();

            frmfeeds = new Pbdms.Forms.Views.FrmViewFeeds();
            frmViewAnItem = new Pbdms.Forms.Views.FrmViewAnItem();
            frmInbox = new Pbdms.Forms.Views.FrmInbox();
            frmFileTransfer = new Pbdms.Forms.Tools.FrmFileTransfers();
            
           
            //involve a thread to listen for request from the network.
            this.Resize += new EventHandler(FrmMain_Resize);
            frmBuddiesStatus = new Pbdms.Forms.Views.FrmBuddyStatus();
            frmBuddiesStatus.MdiParent = this;
            frmKeyManager.MdiParent = this;
            //frmfeeds.MdiParent = this;
            frmFileTransfer.MdiParent = this;
            frmInbox.MdiParent = this;
            frmfeeds.MdiParent = this;
            frmViewAnItem.MdiParent = this;
            
            //added by Chee Hong
            load_friendsList();
         
       
            includePeerTrackorThread();
            
            
            
        }
        //register events
        public void registerEvents()
        {
            Program.networkCtrller.DownloadRequest += new Pbdms.BusinessLogic.Network.NetworkController.DownloadRequestHandler(networkCtrller_DownloadRequest);

            Program.networkCtrller.VerifyKeyResponse += new Pbdms.BusinessLogic.Network.NetworkController.VerifyKeyResponseHandler(networkCtrller_VerifyKeyResponse);
            Program.networkCtrller.InstantMessageReceived += new Pbdms.BusinessLogic.Network.NetworkController.InstantMessageReceivedHandler(networkCtrller_InstantMessageReceived);
            Program.networkCtrller.FileTransferRequestReceived += new Pbdms.BusinessLogic.Network.NetworkController.FileTransferRequestReceivedHandler(networkCtrller_FileTransferRequestReceived);
            Program.networkCtrller.BrowseResultRequestReceived += new Pbdms.BusinessLogic.Network.NetworkController.BrowseResultBuddyReceivedHandler(networkCtrller_BrowseResultRequestReceived);
        }

        void networkCtrller_BrowseResultRequestReceived(object sender, ResultItem obj)
        {
            try
            {
                if (InvokeRequired)
                {
                    BrowseWorker browseWorker = new BrowseWorker(networkCtrller_BrowseResultRequestReceived);
                    this.Invoke(browseWorker, new object[] { sender, obj });
                }
                else
                {
                    //browse results
                    foreach (Form frm in (this.MdiChildren))
                    {
                        frm.WindowState = FormWindowState.Normal;
                        if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmBrowse)))
                        {
                            Pbdms.Forms.Tools.FrmBrowse frmBrowse = (Pbdms.Forms.Tools.FrmBrowse)frm;
                            frmBrowse.addResult(obj);

                            break;
                        }
                    }
                }
            }
            catch
            {
             
            }
            finally
            {

            }
        }
        /// <summary>
        /// download request received from network controller
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        void networkCtrller_DownloadRequest(object sender, NetworkMessage message)
        {
        
                if (InvokeRequired)
                {
                    NetworkMessageHandler networkMessageWorker = new NetworkMessageHandler(networkCtrller_DownloadRequest);
                    this.Invoke(networkMessageWorker, new object[] { sender, message });
                }
                else
                {
                    
                    AuthTcpClient AuthTcpclient = (AuthTcpClient)sender;
                    
                    Buddy buddy= BusinessLogic.DataController.BuddyController.create().selectABuddyBasedOnKeyIDFromDB(AuthTcpclient.getPeerID());
                    //check the existence of the file
                    string []args =message.MessageContent.Split(',');
                    string filename = "";
                    if (args[1].Equals("1"))
                    {
                        Pbdms.Common.DataObject.FileInfo fileInfo = null;

                        fileInfo = BusinessLogic.DataController.FileInfoController.create().getFileInfoObject(args[0]);
                        if (fileInfo != null)
                        {
                            if (fileInfo.Existence == true)
                            {
                                if (fileInfo.Location.Equals(""))
                                {
                                    filename = Common.Global.getLibFolder() + "\\" + fileInfo.FileName;
                                }
                                else
                                {
                                    filename = fileInfo.Location + "\\" + fileInfo.FileName;
                                }
                            }
                        }
                    }
                    else
                    {
                        Pbdms.Common.DataObject.Comment comment = null;
                        comment = BusinessLogic.DataController.CommentController.create().getCommentFromDB(args[0]);
                        if (comment != null)
                        {
                            if (!comment.ReviewFile.Equals(""))
                            {
                                filename = Common.Global.getLibFolder()+"//"+comment.ReviewFile;
                            }
                        }
                    }
                    //file does not exists
                    if (filename.Equals(""))
                    {
                        NetworkMessage netMsg = new NetworkMessage();
                        netMsg.TypeOfMessage = NetworkDealer.NetworkDealer.DOWNLOAD_REQUEST_REJECTED;
                        AuthTcpclient.sendMessage(netMsg);
                        AuthTcpclient.Close();
                        return;
                    }
                    else
                    {
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
                       
                        if (fileInfo.Exists == false)
                        {
                            NetworkMessage netMsg = new NetworkMessage();
                            netMsg.TypeOfMessage = NetworkDealer.NetworkDealer.DOWNLOAD_REQUEST_REJECTED;
                            AuthTcpclient.sendMessage(netMsg);
                            AuthTcpclient.Close();
                            return;
                        }
                    }
                    
                    
                    
                    
                    
                    
                    
                    
                    //if it is from a direct friend
                    if (AuthTcpclient.IsAuthenticated() == true)
                    {
                        BusinessLogic.FileTransfer.LibraryTransferSenderGui librarySender = new Pbdms.BusinessLogic.FileTransfer.LibraryTransferSenderGui(buddy.KeyID, buddy.Name, args[0], args[1], Program.networkCtrller, AuthTcpclient);

                        frmFileTransfer.addControl(librarySender);


                    }
                    else
                    {//not a direct friend
                        Tools.FrmPermission frmPermission = new Pbdms.Forms.Tools.FrmPermission(sender, message, filename);
                        frmPermission.MdiParent = this;
                        frmPermission.Show();
                    }
                }

        }
        /// <summary>
        /// handle key verification results from the network
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        void networkCtrller_VerifyKeyResponse(object sender, NetworkMessage message)
        {
            try
            {
                if (InvokeRequired)
                {
                    NetworkMessageHandler networkMessageWorker = new NetworkMessageHandler(networkCtrller_VerifyKeyResponse);
                    this.BeginInvoke(networkMessageWorker, new object[] { sender, message });
                }

                else
                {
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(KeyVerifyResponse));
                    //deserialize
                    System.IO.StringReader strReader = new System.IO.StringReader(message.MessageContent);
                    KeyVerifyResponse response = (KeyVerifyResponse)serializer.Deserialize(strReader);
                    frmKeyManager.addItem(null, response);
                }
            }
            catch
            {

            }
        }

        void networkCtrller_FileTransferRequestReceived(object sender, NetworkMessage message)
        {
            try
            {
                if (InvokeRequired)
                {
                    NetworkMessageHandler networkMessageWorker = new NetworkMessageHandler(networkCtrller_FileTransferRequestReceived);
                    this.Invoke(networkMessageWorker, new object[] { sender, message });
                }
                
                else
                {
                    //file transfer request
                    Pbdms.Forms.Tools.FrmAcceptFile frmAccept = new Pbdms.Forms.Tools.FrmAcceptFile(sender, message);
                    frmAccept.MdiParent = this;
                    frmAccept.Show();
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// instant messaging handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="message"></param>
        void networkCtrller_InstantMessageReceived(object sender, NetworkMessage message)
        {
            try
            {
                if (InvokeRequired)
                {
                    NetworkMessageHandler networkMessageWorker = new NetworkMessageHandler(networkCtrller_InstantMessageReceived);
                    this.Invoke(networkMessageWorker, new object[] { sender, message });
                }
                else
                {
                    //get friend key id
                    string keyID = message.SenderKeyID;
                    bool found = false;
                    foreach (Form frm in (this.MdiChildren))
                    {
                        if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmInstantMsg)))
                        {
                            Pbdms.Forms.Tools.FrmInstantMsg realFrm = (Pbdms.Forms.Tools.FrmInstantMsg)frm;
                            if (realFrm.getID().Equals(keyID.Trim()))
                            {
                                realFrm.MessageReceived(message.MessageContent);
                                if (realFrm.WindowState == FormWindowState.Minimized)
                                {
                                    FlashWindowEx(realFrm);
                                }
                                found = true;
                                break;
                            }
                        }
                    }
                    //new message
                    if (found == false)
                    {
                        Pbdms.Forms.Tools.FrmInstantMsg fmMsg = new Pbdms.Forms.Tools.FrmInstantMsg();
                        fmMsg.MdiParent = this;

                        Common.DataObject.Buddy buddy = Program.friendControl.getAFriendByKeyID(keyID);
                        fmMsg.setID(buddy.KeyID);
                        fmMsg.setTitle();
                        fmMsg.MessageReceived(message.MessageContent);
                        FlashWindowEx(fmMsg);
                        //fmMsg.Show();
                        fmMsg.WindowState = FormWindowState.Minimized;
                    }
                    AuthTcpClient authClient = (AuthTcpClient)sender;
                    NetworkMessage reply = new NetworkMessage();
                    reply.MessageContent = "";
                    reply.TypeOfMessage = NetworkDealer.NetworkDealer.SEND_A_MESSAGE_REPLY;
                    authClient.sendMessage(reply);
                    authClient.Close();
                }
            }
            catch
            {

            }


                
        }
        
        protected override void OnFormClosed(FormClosedEventArgs e)
        {            
            base.OnFormClosed(e);
    
            if (!isMinimized)
            {
                closePeerTrackor();
                Program.exit();

            }
            
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (!isMinimized)
            {
                int result = Common.Global.showMsgTwoButtons("Are you sure to exit the program?\r\nWarning: The program will close immediatetly and discard all your work after you click 'Yes'", Common.GUI.MsgBoxTwoButtons.YES_NO, 'W');
                if (result == Common.GUI.MsgBoxTwoButtons.DIALOG_RESULT_NO)
                    e.Cancel = true;
                else
                {
                    closePeerTrackor();
                    //frmfeeds.subscManager.saveFeedsToCache();
                    frmInbox.MailBoxManager.saveMessagesToCache();
                    base.OnFormClosing(e);
                    Application.ExitThread();
                }
            }
            else
            {
                e.Cancel = true;
                this.Hide();
                base.OnFormClosing(e);
            }            
        }

        void FrmMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                isMinimized = true;
                Program.notifyIcon1.Visible = true;
                this.ShowInTaskbar = false;
                this.Visible = false;
            }
            else
            {
                isMinimized = false;
            }
        }
       
        /// <summary>
        /// after the main form is rendered, the program should immediately check the library
        /// </summary>
        /// <param name="e"></param>
        protected override void  OnShown(EventArgs e)
        {
            base.OnShown(e);
            //check the library for any files missing
            checkLibraryForFilesMissing("Pbdms - Missing Files in the library");
            
        }      

        private void checkLibraryForFilesMissing(String title)
        {
            //check library
            arlOfMissingFiles = new ArrayList();
            if (hasFileMissingInTheLibrary(ref arlOfMissingFiles) == true)
            {
                if (arlOfMissingFiles!=null && arlOfMissingFiles.Count > 0)
                {
                    DisplayMissingFiles(title);
                }
            }
        }

        
        /// <summary>
        /// Display a list of missing files
        /// </summary>
        private void DisplayMissingFiles(String title)
        {            
            Common.Global.showErrorReporter(arlOfMissingFiles, title);
          
        }

        private bool hasFileMissingInTheLibrary(ref ArrayList arl2)
        {
            bool result = false;
            ArrayList arlItemIDs = BusinessLogic.DataController.ItemController.create().getListOfItemIDs();
            if (arlItemIDs !=null && arlItemIDs.Count>0)
            {
                foreach (object obj in arlItemIDs)
                {
                    Pbdms.Common.DataObject.FileInfo fileInfoObj = BusinessLogic.DataController.FileInfoController.create().getFileInfoObject(obj.ToString());

                    String fileUrl = fileInfoObj.Location + "\\" + fileInfoObj.FileName;

                    if (System.IO.File.Exists(fileUrl))
                    {
                        //update existence status if it was false.
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileUrl);
                        //not the same size
                        if (fileInfo.Length != fileInfoObj.Size)
                        {
                            fileInfoObj.Existence = false;
                            File.Delete(fileUrl);
                            arl2.Add(fileUrl);
                            fileInfoObj.Size = 0;
                            result = true;
                        }
                        else
                        {
                            if (fileInfoObj.Existence == false)
                                fileInfoObj.Existence = true;
                        }
                        BusinessLogic.DataController.FileInfoController.create().updateFileInfoToDB(fileInfoObj);
                    }
                    else
                    {
                        //if the file doesn't exist but the status is "existing"
                        if (fileInfoObj.Existence == true)
                        {
                            arl2.Add(fileUrl);
                            fileInfoObj.Existence = false;
                            fileInfoObj.Size = 0;
                            BusinessLogic.DataController.FileInfoController.create().updateFileInfoToDB(fileInfoObj);
                            result = true;
                            File.Delete(fileUrl);
                        }
                    }

                    //review file
                    Comment commentObj = BusinessLogic.DataController.CommentController.create().getCommentFromDB(obj.ToString());
                    if (!commentObj.ReviewFile.Equals(""))
                    {
                        string filelocation = Common.Global.getLibFolder() + "\\" + commentObj.ReviewFile;
                        if (!System.IO.File.Exists(filelocation))
                        {
                            arl2.Add(filelocation);
                            commentObj.ReviewFile = "";
                            BusinessLogic.DataController.CommentController.create().updateCommentToDB(commentObj);
                            result = true;

                        }
                    }
                }
            }
            return result;
        }

        

        private void mn0204_Click(object sender, EventArgs e)
        {
            viewLibrary();    
        }

        private void mn0102_Click(object sender, EventArgs e)
        {
            closePeerTrackor();
            this.Close();
        
        }

      
     
        private void mn0403_Click(object sender, EventArgs e)
        {
            Pbdms.Forms.Help.frmAbout frmAbt = new Pbdms.Forms.Help.frmAbout();
            frmAbt.ShowDialog();
        }

        

        private void mn0302_Click(object sender, EventArgs e)
        {
            newSearch();
        }

        private void newSearch()
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmSearch)))
                {
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmSearch frmSearch = new Pbdms.Forms.Tools.FrmSearch();
                frmSearch.MdiParent = this;
                frmSearch.Show();
            }
        }

        private void mn0301_Click(object sender, EventArgs e)
        {
            newAdd();
        }

        private void newAdd()
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmAddItem)))
                {
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmAddItem frmSerach = new Pbdms.Forms.Tools.FrmAddItem();
                frmSerach.MdiParent = this;
                frmSerach.WindowState = FormWindowState.Normal;
                frmSerach.Show();
            }
        }

        private void btnLibrary_Click(object sender, EventArgs e)
        {
            viewLibrary();
        }

        private void viewLibrary()
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                //frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Views.FrmLibrary)))
                {
                    frm.WindowState = FormWindowState.Normal;
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Views.FrmLibrary frmlib = new Pbdms.Forms.Views.FrmLibrary();
                frmlib.MdiParent = this;
                frmlib.Show();
            }
        }

        private void tStBtnAdd_Click(object sender, EventArgs e)
        {
            newAdd();
        }

        private void tStBtnSearch_Click(object sender, EventArgs e)
        {
            newSearch();
        }

        private void mn0205_Click(object sender, EventArgs e)
        {
            if (arlOfMissingFiles.Count > 0)
            {
                DisplayMissingFiles("Pbdms - Missing Files in the library");
            }
            else
            {
                Common.Global.showMsgOneButton("There is no missing file in the library",'I');
            }
        }

        

        private void mn0401_Click(object sender, EventArgs e)
        {
            string filePath = Common.Global.startupPath() +"\\Documents\\User Guide.pdf";
            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filePath);
                    psi.UseShellExecute = true;
                    System.Diagnostics.Process.Start(psi);
                }
                catch
                {
                    Common.Global.showMsgOneButton("Unable to open the file, please check the file path", 'C');
                }
            }
        }


        private void FrmMain_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
        #region chee hong new method

       
        public void load_friendsList()
        {
            //Program.FriendControl.setFriendList(BusinessLogic.DataController.BuddyController.create().getListOfBuddies());
            ArrayList friends=BusinessLogic.DataController.BuddyController.create().getListOfBuddies();
            foreach (Common.DataObject.Buddy buddy in friends)
            {
                Verifier verifier = new Verifier();
                
                PgpPublicKey friendPubKey = Program.publicKeyControl.getPublicKey(buddy.KeyID);
                Boolean trusted = false;
                if (friendPubKey != null)
                {
                    foreach (PgpSignature signature in friendPubKey.GetSignaturesOfType(PgpSignature.DirectKey))
                    {
                        trusted = verifier.VerifySignature(signature, Program.keyControl.readSecretKey().PublicKey, friendPubKey.KeyId.ToString("X"));
                        if (trusted == true)
                        {
                            break;
                        }
                    }
                    Common.DataObject.Buddy tmpBuddy = new Buddy(buddy.Id, buddy.Name, buddy.KeyID, null, trusted, false);
                    string temp = "";
                    foreach (string userinfo in friendPubKey.GetUserIds())
                    {
                        temp = userinfo;
                        break;
                    }
                    frmKeyManager.addKey(tmpBuddy.Name, tmpBuddy.KeyID, Common.Global.convertFingerPrint(friendPubKey.GetFingerprint()), temp, trusted);
                    Program.friendControl.addFriend(tmpBuddy);
                    frmBuddiesStatus.peerTrackingManager.addATracker(tmpBuddy.KeyID, tmpBuddy.Trusted);
                }
                else
                {
                    frmKeyManager.addKey(buddy.Name, buddy.KeyID, "public key is missing", "public key is missing", false);
                    Common.DataObject.Buddy tmpBuddy = new Buddy(buddy.Id, buddy.Name, buddy.KeyID, null, false, false);
                    Program.friendControl.addFriend(tmpBuddy);
                    frmBuddiesStatus.peerTrackingManager.addATracker(buddy.KeyID, false);
                }
            }

            
        }
        private void includePeerTrackorThread()
        {
  
            BusinessLogic.PeerMS.IDPublisher idPublisher= new IDPublisher(Program.keyControl);
            Thread thsPublisher = new Thread(new ThreadStart(idPublisher.publish));
            thsPublisher.IsBackground=true;
            thsPublisher.Start();
                
        }
        private void closePeerTrackor()
        {
            if (PeerTrackerThread != null)
            {
                PeerTrackerThread.Abort();
                PeerTrackerThread = null;
            }
      

        }



        private void keyManagementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmKeyManager.WindowState = FormWindowState.Normal;
            frmKeyManager.Activate();

            frmKeyManager.MdiParent = this;
            frmKeyManager.Show();
        }

        private void buddiesStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmBuddiesStatus.Activate();
            frmBuddiesStatus.Show();
        }
        #endregion 



        private void emailAFriendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("mailto:foo@bar.info");
        }

        private void crytographyToolsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmSecurityTools)))
                {
                    frm.WindowState = FormWindowState.Normal;
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmSecurityTools frmSecTools = new Pbdms.Forms.Tools.FrmSecurityTools();
                frmSecTools.MdiParent = this;
                frmSecTools.Show();
            }
        }

        private void addABuddyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                //frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmAddFriend)))
                {
                    frm.WindowState = FormWindowState.Normal;
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmAddFriend frmAddBuddy = new Pbdms.Forms.Tools.FrmAddFriend();
                frmAddBuddy.MdiParent = this;
                frmAddBuddy.Show();
            }
        }



        private void mn01_Click(object sender, EventArgs e)
        {

        }
        // update status on main form
        public void statusReceiver(object sender, EventArgs e)
        {
            
        }

        private void feedsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
                       
                frmfeeds.MdiParent = this;
                frmfeeds.Activate();
                frmfeeds.Show();
            
        }

   
  

  

        private void inboxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmInbox.Activate();
            frmInbox.MdiParent = this;
            frmInbox.Show();
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
           
        }


        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            frmInbox.WindowState =  FormWindowState.Normal;
            frmInbox.Activate();
            frmInbox.MdiParent = this;
            frmInbox.Show();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            frmFileTransfer.Activate();
            frmFileTransfer.MdiParent = this;
            frmFileTransfer.Show();
        }





        private void feedsToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            frmfeeds.WindowState = FormWindowState.Normal;
            frmfeeds.MdiParent = this;
            frmfeeds.Activate();
            frmfeeds.Show();
            
        }

        private void viewFileTransfersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmFileTransfer.WindowState = FormWindowState.Normal;
            frmFileTransfer.Activate();
            frmFileTransfer.Show();
        }


        private void toolStripButton1_Click_2(object sender, EventArgs e)
        {
            frmKeyManager.WindowState = FormWindowState.Normal;
            frmKeyManager.Activate();
            frmKeyManager.Show();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            frmfeeds.WindowState = FormWindowState.Normal;
            frmfeeds.MdiParent = this;
            frmfeeds.Activate();
            frmfeeds.Show();
        }

        private void toolStripButton4_Click_1(object sender, EventArgs e)
        {
            /*
            BusinessLogic.Mail.Message message = new BusinessLogic.Mail.Message();
            message.message = "hi goh";
            Encrypter encry = new Encrypter();
            
            MemoryStream memoryStorage = new MemoryStream();
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            formatter.Serialize(memoryStorage, message);
            memoryStorage.Seek(0, SeekOrigin.Begin);
            MemoryStream output = new MemoryStream();
            output = encry.EncryptBytes(memoryStorage, Program.keyControl.readSecretKey().PublicKey, true);
            string msg = System.Text.Encoding.ASCII.GetString(output.ToArray());
            Decrypter decrypter = new Decrypter();
            MemoryStream decrypStream = new MemoryStream();
            decrypStream = decrypter.DecryptBytes(output, Program.keyControl.readPrivateKey());

            message = (BusinessLogic.Mail.Message)formatter.Deserialize(decrypStream);
            
            /*
            BusinessLogic.Mail.Message message = new BusinessLogic.Mail.Message();
            message.message = "hi goh";
            Signer signer= new Signer();
            
            MemoryStream memoryStorage = new MemoryStream();
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            formatter.Serialize(memoryStorage, message);
            memoryStorage.Seek(0, SeekOrigin.Begin);
            MemoryStream output = new MemoryStream();
            output = signer.SignMemory(memoryStorage, Program.keyControl.readSecretKey(), Program.keyControl.readPrivateKey());
            string msg = System.Text.Encoding.ASCII.GetString(output.ToArray());
            Verifier verifier = new Verifier(Program.publicKeyControl);
            MemoryStream decrypStream = new MemoryStream();
            Common.DataObject.VerifyObjMem verifyMem = verifier.VerifyBytes(output, Program.keyControl.readSecretKey().PublicKey.KeyId.ToString("X"));
            
            message = (BusinessLogic.Mail.Message)formatter.Deserialize(verifyMem.MemData);
            verifyMem.MemData.Close();
             
            //DataAccess.DataProvider.ItemProvider.create(
            //xml.selectMultipleSortedElementValues("/root/Item");
            ArrayList add= BusinessLogic.DataController.ItemController.create().getSortedItems(10);
            BusinessLogic.RSSProcessor.RssProcessor rssProcessor = new BusinessLogic.RSSProcessor.RssProcessor();
            Rss.RssChannel rssfeed=rssProcessor.getsFeed();
            //rssfeed.b
             */
            /*
            string friendKeyID = Program.keyControl.readSecretKey().KeyId.ToString("X");
            
            NetworkMessage message= new NetworkMessage();
            message.TypeOfMessage=NetworkDealer.NetworkDealer.SEND_A_MESSAGE;
            message.MessageContent="dadada";
            client.sendMessage(message);
             * */

            //Pbdms.NetworkDealer.ConnectionHandler connectionHandler = new Pbdms.NetworkDealer.ConnectionHandler(client);
           // Thread ht= new Thread(new ThreadStart(connectionHandler.handleServer(ne));
           // ht.IsBackground = true;
            //ht.Start();
            Pbdms.NetworkDealer.AuthTcpClient client = new Pbdms.NetworkDealer.AuthTcpClient("192.168.129.128", Pbdms.NetworkDealer.NetworkDealer.LISTEN_PORT, "665FD4F7B3316011", Program.keyControl, Program.publicKeyControl, Program.friendControl);
            client.Connect();
            
        }

        private void browseABuddysLibraryCollectionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiChildren))
            {
                frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmBrowse)))
                {
                    frm.WindowState = FormWindowState.Normal;
                    frm.Activate();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmBrowse frmBrowse = new Pbdms.Forms.Tools.FrmBrowse();
                frmBrowse.MdiParent = this;
                frmBrowse.Show();
            }
        }
    }
}